package com.jiang.admin.core.trigger;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jiang.admin.core.config.JobAdminConfig;
import com.jiang.admin.core.model.TriggerParam;
import com.jiang.admin.core.thread.JobThread;
import com.jiang.admin.core.thread.JobThreadManager;
import com.jiang.admin.entity.JobInfo;
import com.jiang.admin.entity.JobLog;
import com.jiang.common.ResultTO;
import com.jiang.common.StatusEnum;

/**
 * 
 * @author jiangyougan 2018年12月2日 下午6:02:09
 *
 */
public class JobTrigger {

	private static Logger logger = LoggerFactory.getLogger(JobTrigger.class);

	public static void trigger(int jobId, String executorParam) {
		JobInfo jobInfo = JobAdminConfig.getAdminConfig().getJobInfoDao().loadById(jobId);
		jobInfo.setExecutorParam(executorParam);
		processTrigger(jobInfo);
	}

	private static void processTrigger(JobInfo jobInfo) {
		// 1、保存日志
		JobLog jobLog = new JobLog();
		jobLog.setJobGroup(jobInfo.getJobGroup());
		jobLog.setJobId(jobInfo.getId());
		jobLog.setServiceId(jobInfo.getServiceId());
		jobLog.setPath(jobInfo.getPath());
		jobLog.setTriggerTime(new Date());
        JobAdminConfig.getAdminConfig().getJobLogDao().save(jobLog);
		logger.debug(">>>>>>>>>>> job trigger start, jobId:{}", jobLog.getId());

		// 2、参数
		TriggerParam triggerParam = new TriggerParam();
		triggerParam.setJobId(jobInfo.getId());
		triggerParam.setServiceId(jobInfo.getServiceId());
		triggerParam.setPath(jobInfo.getPath());
		triggerParam.setExecutorParams(jobInfo.getExecutorParam());
		triggerParam.setLogId(jobLog.getId());
		triggerParam.setLogDateTim(jobLog.getTriggerTime().getTime());

		// 3、执行任务
		ResultTO<String> triggerResult = runExecutor(triggerParam);

		// 4、更新日志信息
		jobLog.setExecutorAddress("");
		jobLog.setExecutorHandler(jobInfo.getExecutorHandler());
		jobLog.setExecutorParam(jobInfo.getExecutorParam());
//        jobLog.setExecutorShardingParam(shardingParam);
//        jobLog.setExecutorFailRetryCount(finalFailRetryCount);
		
		jobLog.setTriggerCode(Integer.valueOf(triggerResult.getCode()));
		jobLog.setTriggerMsg(triggerResult.getMsg());
        JobAdminConfig.getAdminConfig().getJobLogDao().updateTriggerInfo(jobLog);
		logger.debug(">>>>>>>>>>> job trigger end, jobId:{}", jobLog.getId());
	}

	public static ResultTO<String> runExecutor(TriggerParam triggerParam) {
		ResultTO<String> runResult = null;
		try {
			// 1.获取任务线程
			JobThread jobThread = JobThreadManager.getJobThread(triggerParam.getJobId());
			if (jobThread == null) {
				jobThread = JobThreadManager.registryJobThread(triggerParam.getJobId());
			}
			logger.info(">>>>>>>>>>> job trigger get job thread, jobId:{}", triggerParam.getJobId());
			// 2.将任务加入到队列中
			runResult = jobThread.pushTriggerQueue(triggerParam);
			logger.info(">>>>>>>>>>> job trigger push to queue, jobId:{}", triggerParam.getJobId());
		} catch (Exception e) {
			logger.error(">>>>>>>>>>> job trigger error, please check the job thread, jobId:{}", triggerParam.getJobId());
			runResult = ResultTO.fail(StatusEnum.BUSINESS, toString(e));
		}
		runResult.setMsg("触发调度, jobId："+triggerParam.getJobId());
		return runResult;
	}

	private static String toString(Throwable e) {
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		String errorMsg = stringWriter.toString();
		return errorMsg;
	}

}
